package cn.migu.music.hangupsms.common.entity;

/**
 * @version 1.0 created by duanhao@migu.cn on 2022/3/8 11:15 上午
 */

import java.security.MessageDigest;
import java.util.Date;

import org.apache.commons.lang.RandomStringUtils;

import com.alibaba.fastjson.annotation.JSONField;

import cn.migu.music.common.utils.DateTimeConvertor;
import cn.migu.music.common.utils.LogUtils;
import cn.migu.music.hangupsms.common.config.CenterMusicHttpConfigAdapter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 中音接口请求对象
 *
 */
@Data
@Slf4j
public class CenterMusicReq {
    @JSONField(name = "DID")
    private String did;
    @JSONField(name = "SEQ")
    private String seq;
    @JSONField(name = "DIDPwd")
    private String didpwd;

    public CenterMusicReq() {
        String didstr = CenterMusicHttpConfigAdapter.getDid();
        String generateSeq = generateSeq(didstr);
        this.setDid(didstr);
        this.setSeq(generateSeq);
        this.setDidpwd(generateMD5String(generateSeq + CenterMusicHttpConfigAdapter.getPwd()));
    }

    /**
     * 对string进行MD5加密(标准方法)
     *
     * @param string
     *            String
     * @return String
     */
    private static String generateMD5String(String string) {
        String result = "";
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(string.getBytes("UTF8"));
            byte[] s = m.digest();
            for (int i = 0; i < s.length; i++) {
                result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
            }
        } catch (Exception e) {
            LogUtils.info(e, log, "加密失败");
            result = null;
        }
        return result;
    }

    protected static String generateSeq(String did) {
        StringBuilder sb = new StringBuilder();
        sb.append(did);
        sb.append(formatShortDateTime(new Date()));
        sb.append(RandomStringUtils.randomNumeric(8));
        return sb.toString();
    }

    /**
     * 格式日期时间字符串（短格式：yyyyMMddHHmmss）
     *
     * @param date
     *            日期时间
     * @return 日期时间字符串
     */
    private static String formatShortDateTime(Date date) {
        return DateTimeConvertor.format(date, "yyyyMMddHHmmss");
    }
}
